/*
 * Copyright (C) 2010 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.lhlzi.ithink;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.Html;
import android.util.Log;
import android.widget.Toast;

public class Preferences extends PreferenceActivity implements OnPreferenceClickListener {

	/**
	 * Define TAB for track log
	 */
	public static final String TAG = org.lhlzi.ithink.Preferences.class.toString();
	
	
	public static final String VERSION = "versionPreference";
	
	public static final String SERVICE = "servicePreference";
	public static final String AUTO_SERVICE = "autoBootServicePreference";
	public static final String HELP = "helpPreference";
	public static final String ABOUT = "aboutPreference";
	public static final String CHANGELOG = "changelogPreference";
	public static final String WELCOME   = "welcomePreference";
	
	private static final int DIALOG_CHANGELOG = 0;
	private static final int DIALOG_FIRST_TIME   = 1;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		addPreferencesFromResource(R.xml.preferences);
		
		Preference serviceStatusPref = (Preference) findPreference(SERVICE);
		serviceStatusPref.setOnPreferenceClickListener(this);
		
		
		Preference changelogPref = (Preference) findPreference(CHANGELOG);
		changelogPref.setOnPreferenceClickListener(this);
		
		
		Preference welcomePref = (Preference) findPreference(WELCOME);
		welcomePref.setOnPreferenceClickListener(this);
		
		Preference contactDeveloperPref = (Preference) findPreference("contactDeveloperPreference");
		contactDeveloperPref.setOnPreferenceClickListener(this);
		
//		Preference helpPref = (Preference) findPreference("helpPreference");
//		helpPref.setIntent(new Intent(this, org.lhlzi.ithink.ThinkingCaller.class));
//		
//		Preference aboutPref = (Preference) findPreference("aboutPreference");
//		aboutPref.setIntent(new Intent(this, org.lhlzi.ithink.ThinkingCaller.class));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		updateSummaries();
	}
	
	private void updateSummaries() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		Preference item;
		
		boolean boolValue = prefs.getBoolean(SERVICE, false);
		item = (Preference)findPreference(SERVICE);
		if (boolValue)
			item.setSummary(R.string.serv_started);
		else 
			item.setSummary(R.string.serv_stopped);

	}
	
	@Override
	public boolean onPreferenceClick(Preference preference) {
		
		if (preference.getKey().equals(SERVICE)) {
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			Editor prefsEditor = prefs.edit();
			boolean boolValue = prefs.getBoolean(SERVICE, false);
			
			if (!boolValue) {
				if (startService(new Intent(this, org.lhlzi.ithink.RevealService.class)) != null ) {
					prefsEditor.putBoolean(SERVICE, true);
					prefsEditor.commit();
				}
			} else {
				
				stopService(new Intent(this, org.lhlzi.ithink.RevealService.class));
				prefsEditor.putBoolean(SERVICE, false);
				prefsEditor.commit();
				
			}
			
			updateSummaries();
		} else if (preference.getKey().equals(CHANGELOG)) {
			showDialog(DIALOG_CHANGELOG);
		} else if (preference.getKey().equals(WELCOME)) {
			showDialog(DIALOG_FIRST_TIME);
		} else if (preference.getKey().equals("contactDeveloperPreference")) {
			final Intent emailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("mailto:lhlzi@yahoo.cn")); 
			try {
				startActivity(emailIntent);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(this, R.string.error_email, Toast.LENGTH_LONG).show();
			}
		}
		return false;
	}
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			
		case DIALOG_CHANGELOG:
			StringBuilder changelog = new StringBuilder();
			BufferedReader input;
			try {
				InputStream is = getResources().openRawResource(R.raw.changelog);
				input = new BufferedReader(new InputStreamReader(is));
				String line;
				while ((line = input.readLine()) != null) {
					changelog.append(line);
					changelog.append("<br/>");
				}
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return new AlertDialog.Builder(this)
			.setTitle(R.string.changelog_title)
			.setMessage(Html.fromHtml(changelog.toString()))
			.setPositiveButton(R.string.close, null)
			.create();
			
			
		case DIALOG_FIRST_TIME:
			return new AlertDialog.Builder(this)
			.setTitle(R.string.welcome_to_ithink)
			.setMessage(R.string.welcome_to_ithink_msg)
			.setPositiveButton(R.string.close, null)
			.create();
		}
		
			
		return null;
	}


}
